package hotel.quartz.oversea.job;

import cn.hutool.core.date.DateUtil;
import hotel.quartz.oversea.config.service.RedisService;
import hotel.quartz.oversea.entity.form.JobForm;
import hotel.quartz.oversea.job.base.BaseJob;
import hotel.quartz.oversea.service.impl.JobAndTriggerServiceImpl;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Date;

/**
 * <p>
 * Hello Job 调用admin feign 接口相关案例
 * </p>
 *
 * @description: Hello Job
 * @author: Zhang·JZ
 * @date: 2020-05-18 13:22
 * @version: V1.0
 */
@Slf4j
public class HelloJob implements BaseJob {

    @Autowired
    private JobAndTriggerServiceImpl jobAndTriggerService;

    @Autowired
    private RedisService redisService;

    private int count =0;


    @Autowired
    private RedisTemplate redisTemplate;


    private String jobGroupName = "HELLO";
    private String jobClassName = this.getClass().getName();
    private String timestamp = "Mhdnrs"+String.valueOf(System.currentTimeMillis());

    @SneakyThrows
    @Override
    public void execute(JobExecutionContext context) {

        if(redisService.exists("hello_job_count")){
            count = Integer.valueOf(redisService.get("hello_job_count").toString());
        }
        count++;
        redisService.set("hello_job_count",count);

//        RestTemplate template = new RestTemplate();
        log.info("---{} ---》 Hello Job 执行开始时间: {}",count, DateUtil.now());
        int time = 10;
        int tempT = time/5;
        log.warn("i/5: {}", tempT);
        if(tempT > 0){
//            JobForm jobForm = new JobForm();
//            jobForm.setJobClassName("hotel.quartz.job.HelloJob");
//            jobForm.setJobGroupName("Meituan");
//            jobForm.setCronExpression("*/"+tempT+" * * * * ?");
//
//            log.warn("jobForm: {}", JacksonUtil.objectToJson(jobForm));
//            jobAndTriggerService.cronJob(jobForm);
//            Thread.sleep(11000);
        }
//        String url = "http://192.168.1.10:8080/api/admin/user/info/admin?access_token=9d350e87-0d57-48f2-a2f8-628597483259";
//        Result<SysUser> sysUserResult = template.getForObject(url, Result.class);
//        log.info("retStr {}",sysUserResult);

        resetJob();
        log.info("---{} ---》 Hello Job 执行结束时间: {}",count, DateUtil.now());
    }

    public void resetJob(){

        log.info("进入 ---》 resetJob");
//        if(null != redisTemplate.opsForValue().get("HelloJob_updateCronTimeTodo")){
            String curTime = hotel.base.oversea.utils.DateUtil.getCurrTime();
            String doTime = (String)redisTemplate.opsForValue().get("HelloJob_updateCronTimeTodo_time");
            if(null == doTime){
                doTime = "30";
            }

            Date date = hotel.base.oversea.utils.DateUtil.addSecond(curTime,Integer.valueOf(doTime));
            String execuTime = hotel.base.oversea.utils.DateUtil.formatDate(date,"ss mm HH");
            /*try {
                Thread.currentThread().sleep(1000*30);//30秒
            } catch (InterruptedException e) {
                log.error(e.getMessage(),e);
            }*/
            cronJob(execuTime+" * * ?",doTime);//cronJob第一次都会进来 则干脆sleep来控制时间  DateUtil.addSecond(curTime,60); 定个长时间实际不起作用
//        }
    }

    public void cronJob(String cron,String doTime){
        log.info("进入 ---》 cronJob");
        //已最后一页，暂停定时器,删除rediskey
        JobForm jobForm = new JobForm();
        jobForm.setJobClassName(jobClassName);
        jobForm.setJobGroupName(jobGroupName);
        jobForm.setCronExpression(cron);
        try {
            jobAndTriggerService.cronJob(jobForm);
            log.info("Hello Job 程序触发"+doTime+"秒后继续执行");
        } catch (Exception e) {
            log.error("Hello Job {} 执行cronJob异常: {}",timestamp,jobForm);
            log.error(e.getMessage(),e);
            try {
                Thread.sleep(5000);
                log.error("Hello Job {} 再次执行cronJob",timestamp);
                jobAndTriggerService.cronJob(jobForm);
            } catch (Exception e2) {
                log.error(e2.getMessage(), e2);
                //SendUtils.dingMsg("【主动查询产品定时器出现异常，请核实！】", e2.getMessage(),99,);
            }
        }
    }
}
